//
// Created by 32827 on 2024/1/13.
//
#include "yzl_xpt2046.h"
#ifdef YZL_XPT2046_ENABLE
struct YZL_Soft_SPI softSpi;
void yzl_xpt2046_screen_touch_init(YZL_GPIO cs,YZL_GPIO clk,YZL_GPIO miso,YZL_GPIO mosi,YZL_GPIO intp){

    GPIO_InitTypeDef gpioInitTypeDef;
    gpioInitTypeDef.Pin = intp.pin;
    gpioInitTypeDef.Mode = GPIO_MODE_INPUT;
    gpioInitTypeDef.Pull = GPIO_PULLUP;
    HAL_GPIO_Init(intp.port, &gpioInitTypeDef);

    softSpi.MSB=YZF_TRUE;
    softSpi.cs=cs;
    softSpi.miso=miso;
    softSpi.mosi=mosi;
    softSpi.clk=clk;
    softSpi.mode=YZL_SOFTPORT_SPI_MODE_0;

    yzl_softport_spi_init(&softSpi);
}
uint16_t yzl_xpt2046_screen_touch_adc_x(){
    yzl_softport_spi_start(&softSpi);
    yzl_softport_spi_transmit_byte8(&softSpi, 0xd0);
    uint16_t dx=yzl_softport_spi_transmit_byte16(&softSpi, 0x0000);
    yzl_softport_spi_end(&softSpi);
    return dx;
}
uint16_t yzl_xpt2046_screen_touch_adc_y(){
    yzl_softport_spi_start(&softSpi);
    yzl_softport_spi_transmit_byte8(&softSpi, 0x90);
    uint16_t dy=yzl_softport_spi_transmit_byte16(&softSpi, 0x0000);
    yzl_softport_spi_end(&softSpi);
    return dy;
}
//上左 上右 下右 下左
void yzl_xpt2046_screen_touch_convert_point(struct YZL_TouchPoint *point, uint16_t ReMapData[4][2]){
    uint32_t avx=(ReMapData[1][0]-ReMapData[0][0]+ReMapData[2][0]-ReMapData[3][0])/2;
    uint32_t avy=(ReMapData[1][1]-ReMapData[2][1]+ReMapData[0][1]-ReMapData[3][1])/2;
    uint32_t rex=(ReMapData[3][0]+ReMapData[0][0])/2;
    uint32_t rey=(ReMapData[2][1]+ReMapData[3][1])/2;

    point->x=(point->x-rex)/(avx/240);
    point->y=(point->y-rey)/(avy/320);
}
__weak void yzl_xpt2046_screen_touch_callback(uint16_t x, uint16_t y){

}
#endif